package br.slic.listener;

import java.io.IOException;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpSession;

import br.slic.entidade.UsuarioSistema;
import br.slic.util.SLICWebConstantes;

public class AutenticacaoListener implements PhaseListener {

	private static final long serialVersionUID = 9052753997813124068L;

	@Override
	public void afterPhase(PhaseEvent arg0) {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		ExternalContext context = facesContext.getExternalContext();
		
		String[] nomePagina = SLICWebConstantes.PAGINA_LOGIN.split("\\.");
		boolean isPaginaLogin = (facesContext.getViewRoot().getViewId().lastIndexOf(nomePagina[0]) > -1);
		HttpSession session = (HttpSession) context.getSession(true);
		UsuarioSistema usuarioSistema = (UsuarioSistema) session.getAttribute(SLICWebConstantes.SESSAO_USUARIO);
		
		if (usuarioSistema == null && !isPaginaLogin) {
			try {
				context.redirect(SLICWebConstantes.PAGINA_LOGIN);
			} catch (IOException e) {
				e.printStackTrace();
			}	
		}
	}

	@Override
	public void beforePhase(PhaseEvent arg0) {
	}

	@Override
	public PhaseId getPhaseId() {
		return PhaseId.RESTORE_VIEW;
	}

}
